#include "scicalc.h"
#include <stdlib.h>
#include <stdio.h>

// Sparse matrix element structure
typedef struct {
    int row;
    int col;
    double value;
} SparseElement;

// Convert dense matrix to sparse format
SparseElement* dense_to_sparse(double** matrix, int rows, int cols, int* count) {
    *count = 0;
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            if(matrix[i][j] != 0) {
                (*count)++;
            }
        }
    }
    
    SparseElement* sparse = malloc(*count * sizeof(SparseElement));
    if(!sparse) return NULL;
    
    int index = 0;
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            if(matrix[i][j] != 0) {
                sparse[index].row = i;
                sparse[index].col = j;
                sparse[index].value = matrix[i][j];
                index++;
            }
        }
    }
    
    return sparse;
}

// Convert sparse matrix to dense format
double** sparse_to_dense(SparseElement* sparse, int count, int rows, int cols) {
    double** matrix = malloc(rows * sizeof(double*));
    if(!matrix) return NULL;
    
    for(int i = 0; i < rows; i++) {
        matrix[i] = calloc(cols, sizeof(double));
        if(!matrix[i]) {
            return NULL;
        }
    }
    
    for(int i = 0; i < count; i++) {
        matrix[sparse[i].row][sparse[i].col] = sparse[i].value;
    }
    
    return matrix;
}